package subumbo.micro.controller
{
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	/**
	 * Central Notification Centre decoupled from the displaylist. 
	 * @author patrickwolleb
	 * 
	 */	
	
	public class EventCentre
	{
		private var _listeners:Dictionary = new Dictionary();
		
		
		public function dispatch(e:Event):Boolean
		{
			var i:int;
			var callbacks:Array = _listeners[e.type] as Array;
			if(callbacks)
			{
				i = callbacks.length;
				while( --i > -1 )
				{
					callbacks[i].call(this,e);
				}
				return true;	
			}else return false;
		}
		
		/**
		 * Adds event to the _listeners array of specified event type. 
		 * @param eventName Type of the event statically available in ApplicationEvent class.
		 * @param callback Callback function pointer
		 * 
		 */		
		public function addEventListener(eventName:String, callback:Function):void
		{
			if(!_listeners[eventName]) _listeners[eventName] = [callback];
			else (_listeners[eventName] as Array).push(callback);
		}
		
		
		/**
		 * Removes event from the _listeners array of specified event type. 
		 * @param eventName Type of the event statically available in ApplicationEvent class.
		 * @param callback Callback function pointer
		 * @return Returns true if removed or false oif failed. 
		 * 
		 */		
		public function removeEventListener(eventName:String, callback:Function):Boolean
		{
			var callbacks:Array;
			var _callback:Function;
			var i:int;
			if(!_listeners[eventName]) return false;
			else 
			{
				callbacks = _listeners[eventName];
				i = callbacks.length;
				while( --i > -1 )
				{
					_callback = callbacks[i];
					if(_callback == callback)
					{
						 callbacks.splice(i,1);	
						 return true;
					}
				}				 
			}
			return false;
		}
		
		
		static private const _instance:EventCentre = new EventCentre();
		static public function get instance():EventCentre
		{
			return _instance;
		}
	}
}